var obj = {
    pagenum:1,
    pagesize:2,
    cate_id:'',
    state:'',
};
// 日期、时间过滤器
template.defaults.imports.dateformat = function(time){
    var dt = new Date(time);
    var y = dt.getFullYear();
    var m = (dt.getMonth()+1).toString().padStart(2,'0');
    var d = (dt.getDate()).toString().padStart(2,'0');
    var hh = (dt.getHours()).toString().padStart(2,'0');
    var mm = (dt.getMinutes()).toString().padStart(2,'0');
    var ss = (dt.getSeconds()).toString().padStart(2,'0');
    var str =  `${y}-${m}-${d}  ${hh}:${mm}:${ss}`;
    return str;
}
//入口函数
$(function(){
    
    initTable();
    initCate();
    $('#form-search').on('submit',function(e){
        e.preventDefault();
        obj.cate_id = $('[name="cate_id"]').val();
        obj.state = $('[name="state"]').val();
        initTable();
    });
    $('tbody').on('click','.remove',function(){
        var id = $(this).attr('data-id');
        layer.confirm('确定删除？',{icon:3,title:'提示'},function(index){
            $.ajax({
                type:'get',
                url:'/my/article/delete/'+id,
                success:function(res){
                    if (res.status != 0) return layer.msg('删除失败');
                    layer.msg('删除成功');
                    如果当前页全被删除就显示前一夜=页内容
                    if ($('.remove').length == 1){
                        obj.pagenum = obj.pagenum == 1?1:obj.pagenum - 1;
                    }
                    initTable();
                }
            })
            layer.close(index);
        })
    })
    

})
//渲染表格数据
function initTable(){
    $.ajax({
        type:'get',
        url:'/my/article/list',
        data:obj,       
        success:function(res){
            if (res.status != 0)return layer.msg('获取数据失败');
            var str = template('tpl',res);
            $('tbody').html(str);
            renderPage(res.total);
        }
    })
} ;
//渲染下拉框数据
function initCate(){
    $.ajax({
        type:'get',
        url:'/my/article/cates',
        success:function(res){
            if (res.status != 0) return layer.msg('获取下拉数据失败');
            var str = template('tpl-cate',res);
            $('[name="cate_id"]').html(str);
            //重新渲染下拉框表单
            layui.form.render('select');
        }
    })
};
// 分页函数
function renderPage(total){
    layui.laypage.render({
        elem:'pageBox',
        count:total,
        limit:obj.pagesize,
        curr:obj.pagenum,
        limits:[1,2,3,4,5],
        layout:['count','limit','prev','page','next','skip'],
        jump:function(objs,first){
            obj.pagenum = objs.curr;
            obj.pagesize = objs.limit;
            if (!first){
                initTable();
            }
        }
    })
}